package com.bdqn.mzc.service.impl;

import com.bdqn.mzc.excep.NotEnoughException;
import com.bdqn.mzc.excep.UserException;
import com.bdqn.mzc.mapper.*;
import com.bdqn.mzc.model.*;
import com.bdqn.mzc.model.dto.PayDto;
import com.bdqn.mzc.model.dto.UpdateUserDto;
import com.bdqn.mzc.service.UserService;
import com.bdqn.mzc.utils.Email;
import com.bdqn.mzc.utils.IdEntityCard;
import com.bdqn.mzc.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.security.GeneralSecurityException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IndentMapper indentMapper;

    @Autowired
    private TravelmemberMapper travelmemberMapper;

    @Autowired
    private ScenicspotMapper scenicspotMapper;

    @Autowired
    private ValuateMapper valuateMapper;

    @Override
    public User login(String account,String password) throws Exception {
        User user=null;
        boolean isEmail= Email.isEmail(account);
        if (isEmail){
            user= userMapper.selectByEmail(account);
        }else {
            user=userMapper.selectByGofar(account);
        }
        if (user==null){
            throw new UserException("Gofar账号或邮箱有误");
        }
        if (!user.getUserPassword().equals(password)){
            throw new UserException("密码错误");
        }
        return user;
    }

    @Override
    public List<User> selectList() {
        return userMapper.selectList();
    }

    @Override
    public int register(String email,String password,String code) throws Exception {
        //根据email查询判断邮箱是否存在
        User isEmalUser= userMapper.selectByEmail(email);
        if (isEmalUser!=null){
            throw new UserException("该邮箱已被注册");
        }
        if (!Email.CODE6.equals(code)){
            throw new UserException("您输入的验证码有误");
        }
        User user=new User();
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取系统当前时间
        String time = df.format(new Date());
        //随机生成gofaraccount账号,转为String类型
        int gofaraccount = ((int)((Math.random()*9+1)*1000000000));
        String gofaraccountString=String.valueOf(gofaraccount);
        user.setUserGofaraccount(gofaraccountString).setUserEmail(email)
                .setUserPassword(password).setUserRegtime(time).setTravelmemberId(0);
        return userMapper.insertSelective(user);
    }

    @Override
    public String sandCode(String email) throws Exception {
        String code="";
        try {
           code= Email.sendCodeToQQEail(email);
           Email.CODE6=code;
        } catch (MessagingException e) {
            throw new NotEnoughException("邮箱异常");
        } catch (GeneralSecurityException e) {
            throw new NotEnoughException("邮箱异常");
        }
        return code;
    }

    @Override
    public int updatePersonal(UpdateUserDto updateUserDto, Integer id){
        User user=new User();
        //根据id修改
        user.setUserId(id);
        //如果身份证号码不为空
        if (updateUserDto.getUserIdentitycard()!=null){
            //如果性别为空
            if (updateUserDto.getUserGender()==null){
                //调用工具类通过身份证号解析性别
                String gender= IdEntityCard.getGenderByIdCard(updateUserDto.getUserIdentitycard());
                String sex="";
                if ("1".equals(gender)){
                    sex="男";
                }else if ("2".equals(sex)){
                    sex="女";
                }else {
                    sex="未知";
                }
                user.setUserGender(sex);
            }
            //如果年龄为空
            if (updateUserDto.getUserAge()==null){
                //调用工具类通过身份证号解析年龄
                int age= IdEntityCard.getAgeByIdCard(updateUserDto.getUserIdentitycard());
                user.setUserAge(age);
            }
        }
        return userMapper.updateByPrimaryKeySelective(user);
    }

    @Override
    public User selectPersonalById(Integer id) {
        return userMapper.selectLoginUserAndTravelmember(id);
    }

    @Override
    @Transactional
    public int buyTicket(HttpServletResponse response, HttpServletRequest request, Integer scenicspotId) throws Exception {
        //获取已登录用户的id
        int id= JWTUtils.getUserId(request);
        //根据已登录的用户id查询出用户信息
        User user= userMapper.selectByPrimaryKey(id);
        //更新消费金额
        int travel=0;
        if (user.getMonetary()>=2000&&user.getMonetary()<10000){
            travel=1;
        }else if (user.getMonetary()>=10000&&user.getMonetary()<50000){
            travel=2;
        }else if (user.getMonetary()>=50000&&user.getMonetary()<80000){
            travel=3;
        }else if (user.getMonetary()>=80000&&user.getMonetary()<200000){
            travel=4;
        }else if (user.getMonetary()>200000){
            travel=5;
        }
        //根据会员卡等级拿到对应的id
        Travelmember newTravel = travelmemberMapper.selectByRank(travel);
        //修改为最新的会员信息
        User newUser=new User();
        newUser.setUserId(user.getUserId()).setTravelmemberId(newTravel.getTravelmemberId());
        int rst= userMapper.updateByPrimaryKeySelective(newUser);
        User ultimatelyUser=null;
        if (rst>0){
           ultimatelyUser= userMapper.selectByPrimaryKey(newUser.getUserId());
        }
        //根据已登录的用户的会员卡id拿到会员卡信息
        Travelmember travelmember= travelmemberMapper.selectByPrimaryKey(ultimatelyUser.getUserId());
        Double discount=0.0;
        if (travelmember.getTravelmemberIntegral()==9){
            discount=0.9;
        }else if (travelmember.getTravelmemberIntegral()==8){
            discount=0.8;
        }else if (travelmember.getTravelmemberIntegral()==7){
            discount=0.7;
        }else if (travelmember.getTravelmemberIntegral()==6){
            discount=0.6;
        }else if (travelmember.getTravelmemberIntegral()==3){
            discount=0.3;
        }
        //根据景区id获取到景区信息
        Scenicspot scenicspot= scenicspotMapper.selectScenicspotById(scenicspotId);
        if (scenicspot==null){
            throw new NotEnoughException("该景区不存在");
        }
        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取系统当前时间
        String time = df.format(new Date());
        Double pr=0.0;
        if (discount!=0.0){
            pr=scenicspot.getScenicspotPrice()*discount;
        }
        pr=scenicspot.getScenicspotPrice();
        if (ultimatelyUser.getUserAge()!=null){
            if (ultimatelyUser.getUserAge()>18){
                pr=pr-20;
            }
        }
        PayDto payDto=new PayDto();
        String no= String.valueOf(System.currentTimeMillis());
        payDto.setNo(no);
        payDto.setPrice(pr);
        payDto.setName(scenicspot.getScenicspotName());
        //支付宝支付方法
        //AliPay.pay(payDto,response);
        Indent indent=new Indent();
        indent.setUserId(ultimatelyUser.getUserId());
        indent.setIndentNo(no);
        indent.setIndentPrice(pr);
        indent.setScenicspotId(scenicspot.getScenicspotId());
        indent.setIndentSelldata(time);
        indent.setIndentType(1);
        int count= indentMapper.insertSelective(indent);
        return count;
    }

    @Override
    public List<Indent> selectindentAll() {
        return indentMapper.selectAll();
    }

    @Override
    public int updateIndentById(Integer id) {
        Indent indent=new Indent();
        indent.setIndentId(id);
        indent.setIndentType(2);
        return indentMapper.updateByPrimaryKeySelective(indent);
    }


    public int updateIndentById2(Integer id){
        Indent indent=new Indent();
        indent.setIndentId(id);
        indent.setIndentType(3);
        return indentMapper.updateByPrimaryKeySelective(indent);
    }


    @Override
    public int deleteIndentById(Integer id) throws Exception {
        Indent indent=indentMapper.selectByPrimaryKey(id);
        if (indent.getIndentType()!=3){
            throw new NotEnoughException("该订单不能进行此操作");
        }
        return indentMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insertValuate(Integer IndentId,double grade,String content) throws Exception {
        Indent indent=indentMapper.selectByPrimaryKey(IndentId);
        if (indent.getIndentType()!=3){
            throw new NotEnoughException("该订单不能进行此操作");
        }
        Valuate v=new Valuate();
        v.setUserId(indent.getUserId());
        v.setIndentId(indent.getIndentId());
        v.setScenicspotId(indent.getScenicspotId());
        v.setValuateGrade(grade);
        v.setValuateContent(content);
        return valuateMapper.insertSelective(v);
    }


}
